import {
  TODO_ADD,
  TODO_CHANGE_DONE,
  TODO_CHANGE_TYPE,
  TODO_DEL,
  TODO_DEL_DONE,
} from '../actions/actionTypes'

const initState = {
  list: [
    { id: 1, content: '吃饭', done: true },
    { id: 2, content: '睡觉', done: false },
    { id: 3, content: '打代码', done: true },
  ],
  type: 'all',
  channels: [],
}

// reducer函数签名：(state, action) => newState
export const todoReducer = (state = initState, action) => {
  switch (action.type) {
    // 根据 id 删除数据
    case TODO_DEL:
      return { ...state, list: state.list.filter((v) => v.id !== action.payload) }
    // 根据 id 更新完成状态
    case TODO_CHANGE_DONE:
      return {
        ...state,
        list: state.list.map((item) => {
          if (item.id === action.payload) {
            return { ...item, done: !item.done }
          } else {
            return item
          }
        }),
      }
    // 删除已完成任务
    case TODO_DEL_DONE:
      return { ...state, list: state.list.filter((v) => !v.done) }
    // 高亮切换效果
    case TODO_CHANGE_TYPE:
      return { ...state, type: action.payload }
    // 新增待办任务
    case TODO_ADD:
      return { ...state, list: [action.payload, ...state.list] }
    // 切换全选状态
    case 'saveChannel':
      return { ...state, channels: action.payload }
    // ...
    default:
      return state
  }
}
